﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IRCServer.Entities.Commands;
using IRCServer.Backend;
using IRCServer.Entities;
using IRCServer.Utilities;

namespace IRCServer.CommandHandlers
{
    class USERCommandHandler: CommandHandlerBase
    {
        public override string HandleCommand(IRCCommandBase command, Session session)
        {
            if (command is USERCommand)
            {
                USERCommand userCommand = (USERCommand)command;

                if (userCommand.Username == null || userCommand.Realname == null || userCommand.Hostname == null)
                {
                    return Errors.GetErrorResponse(ErrorCode.ERR_NEEDMOREPARAMS, CommandParser.USERCommand);
                }

                if (session.User ==  null || session.User.Username == null)
                {
                    if (session.User != null)
                    {
                        session.User.Username = userCommand.Username;
                        session.User.Realname = userCommand.Realname;
                        session.User.Hostname = userCommand.Hostname;
                    }
                    else
                    {
                        session.User = new User()
                        {
                            Username = userCommand.Username,
                            Realname = userCommand.Realname,
                            Hostname = userCommand.Hostname
                        };
                        ServerBackend.Instance.Users.Add(session.User);
                    }

                    UpdateConnectionState(session);

                    return "OK";
                }
                else
                {
                    return Errors.GetErrorResponse(ErrorCode.ERR_ALREADYREGISTERED,String.Empty);
                }
            }
            else
            {
                throw new ArgumentException();
            }
        }
    }
}
